//
//  SPTiledView.m
//  SPMapKit
//
//  Created by zhangbo on 2017/9/7.
//  Copyright © 2017年 zhangbo. All rights reserved.
//

#import "SPTiledView.h"
#import <QuartzCore/QuartzCore.h>
#import "MapAlgorithm.h"

@implementation SPTiledView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame])
    {
        CGSize scaledTileSize = CGSizeApplyAffineTransform(CGSizeMake(kDefaultTileSize, kDefaultTileSize), CGAffineTransformMakeScale(self.contentScaleFactor, self.contentScaleFactor));
        self.tiledLayer.tileSize = scaledTileSize;
    }
    return self;
}

+ (Class) layerClass
{
    return [CATiledLayer class];
}

- (CATiledLayer *)tiledLayer
{
    return (CATiledLayer *)self.layer;
}

-(void) setNumberOfZoomLevels:(int)numberOfZoomLevels
{
    self.tiledLayer.levelsOfDetailBias = numberOfZoomLevels;
}

-(int) numberOfZoomLevels
{
    return (int) self.tiledLayer.levelsOfDetailBias;
}

-(void) drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGFloat scale = CGContextGetCTM(ctx).a / self.layer.contentsScale;
//    NSLog(@"%f", scale);
    
    NSInteger row = (NSInteger)((CGRectGetMinX(rect) * scale) / kDefaultTileSize);
    NSInteger col = (NSInteger)((CGRectGetMinY(rect) * scale) / kDefaultTileSize);
    
    UIImage *tile_image = [self.delegate tiledView:self imageForRow:row column:col scale:(NSInteger)scale];
    [tile_image drawInRect:rect];
    
//    [self annotateRect:rect inContext:ctx];
}

- (void)annotateRect:(CGRect)rect inContext:(CGContextRef)ctx
{
    CGFloat scale = CGContextGetCTM(ctx).a / self.tiledLayer.contentsScale;
    CGFloat line_width = 2.0f / scale;
    CGFloat font_size = 16.0f / scale;
    
    NSInteger col = (NSInteger)((CGRectGetMinX(rect) * scale) / kDefaultTileSize);
    NSInteger row = (NSInteger)((CGRectGetMinY(rect) * scale) / kDefaultTileSize);
    
    [[UIColor whiteColor] set];
    [[NSString stringWithFormat:@" %0.0f  %d  %d", log2f(scale), row, col] drawAtPoint:CGPointMake(CGRectGetMinX(rect), CGRectGetMinY(rect)) withFont:[UIFont boldSystemFontOfSize:font_size]];
    
    [[UIColor redColor] set];
    CGContextSetLineWidth(ctx, line_width);
    CGContextStrokeRect(ctx, rect);
}

@end
